﻿using Android.App;
using Android.Runtime;
using Android.Views;
using Serilog;
namespace AnyTap;

[Application]
public class MainApplication : MauiApplication
{
	private bool unhandled = false;
	public MainApplication(IntPtr handle, JniHandleOwnership ownership)
		: base(handle, ownership)
	{
		TaskScheduler.UnobservedTaskException += (s, e) => UnhandledExit($"UnobservedTaskException\n{e.Exception}");
		AppDomain.CurrentDomain.UnhandledException += (s, e) => Log.Fatal($"UnhandledException\n{e.ExceptionObject}");
		AndroidEnvironment.UnhandledExceptionRaiser += (s, e) => { UnhandledExit($"UnhandledExceptionRaiser\n{e.Exception}"); e.Handled = true; };
	}

	protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

	/// <summary>
	/// 异常退出回调
	/// </summary>
	/// <param name="msg">故障信息</param>
	private void UnhandledExit(string msg)
	{
		if(unhandled)
			return;

		unhandled = true;
		Log.Fatal(msg);
		MainThread.BeginInvokeOnMainThread(delegate
		{
			var dlg = new AlertDialog.Builder(this).Create();
			dlg.SetMessage(msg);
			dlg.SetTitle("程序异常!");
			dlg.SetCanceledOnTouchOutside(false);
			dlg.SetButton("OK", (s, e) => Java.Lang.JavaSystem.Exit(0));
			dlg.Window.SetType(OperatingSystem.IsAndroidVersionAtLeast(26) ? WindowManagerTypes.ApplicationOverlay : WindowManagerTypes.SystemAlert);
			dlg.Show();
		});
	}
}
